package com._9xcloud.leaverequest.web;

import javax.servlet.*;

import com._9xcloud.leaverequest.web.config.RootContextConfiguration;
import com._9xcloud.leaverequest.web.config.WebMvcContextConfiguration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import java.util.EnumSet;

/**
 * Created by hyq on 2015/6/11.
 */
public class ApplicationInitializer implements WebApplicationInitializer {
    private static final String WEB_API_DISPATCHER_SERVLET_NAME = "web-api-dispatcher";
    private static final String WEB_API_DISPATCHER_URL_PATTERN = "/api/*";
    private static final String ENCODING_FILTER_NAME="encodingFilter";
    private static final String ENCODING_NAME="utf-8";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        registerListener(servletContext);
        registerDispatcherServlet(servletContext);
        //registerEncodingFilter(servletContext);
    }

    private void registerEncodingFilter(ServletContext servletContext) {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding(ENCODING_NAME);
        FilterRegistration.Dynamic f = servletContext.addFilter(ENCODING_FILTER_NAME, filter);
        f.addMappingForUrlPatterns(EnumSet.range(DispatcherType.FORWARD, DispatcherType.ERROR), false, "dd");
    }

    private void registerListener(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext rootContext = createContext(RootContextConfiguration.class);
        ContextLoaderListener listener = new ContextLoaderListener(rootContext);
        servletContext.addListener(listener);
    }

    private void registerDispatcherServlet(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext dispatcherContext = createContext(WebMvcContextConfiguration.class);
        Servlet dispatcherServlet = new DispatcherServlet(dispatcherContext);
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(WEB_API_DISPATCHER_SERVLET_NAME, dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping(WEB_API_DISPATCHER_URL_PATTERN);
    }

    private AnnotationConfigWebApplicationContext createContext(final Class<?>... annotatedClasses) {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(annotatedClasses);
        return context;
    }

}
